package org.wzq;

import java.util.List;

/**
 * author:wzq
 * date:16-6-8
 * project:thread
 * description: TODO
 */
public class Consumer implements Runnable {

    private final List<Object> container;
    private final int id;

    public Consumer(List<Object> container, int id) {
        this.container = container;
        this.id = id;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (container) {
                System.out.println("Consumer " + id + " enter critic zone");
                if (container.size() == 0) {
                    System.out.println("Consumer " + id + " empty wait");
                    try {
                        container.wait();
                    } catch (InterruptedException ex) {
                        System.out.println("Consumer " + id + " wake up");
                    }
                }
                System.out.println("Consumer " + id + " leave critic zone");
            }

            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                System.out.println("Consumer " + id + " Interrupted Exception from sleep");
            }

            synchronized (container) {
                if (container.size() > 0) {
                    Object obj = container.remove(0);
                    System.out.println("Consumer " + id + " get item to container : " + obj);
                    // notify consumer
                    container.notify();
                }
            }
        }
    }
}
